import {
  registerMicroApps,
  start,
  runAfterFirstMounted,
  setDefaultMountApp,
  initGlobalState,
  prefetchApps,
  addGlobalUncaughtErrorHandler,
  loadMicroApp,
} from "qiankun";
import Vue from "vue";

class MicroAppModule {
  constructor() {
    return this;
  }
  createRouter(props) {
    registerMicroApps(props);
    return this;
  }
  createStore(props) {
    let state = props.state || {};
    const actions = initGlobalState(state);
    actions.onGlobalStateChange((state, prev) => {
      console.log("[主应用][状态变化]", state, prev);
    });
    Vue.prototype.$actions = actions;
    return this;
  }
  setDefaultMountApp(props) {
    props && setDefaultMountApp(props); //设置主应用启动后默认进入的微应用
    return this;
  }
  prefetchApps(props) {
    props && prefetchApps(props); //预加载微应用列表
    return this;
  }
  start(props) {
    start(props || {});
    runAfterFirstMounted(() => {
      console.log("[主应用][第一个微应用启动成功]");
    });
    return this;
  }
  startMicroApp(app, config) {
    return loadMicroApp(app, config);
  }
}

class MicroApp {
  constructor(props) {
    return new Promise((resolve, reject) => {
      try {
        if (props && props.install) {
          const microApp = new MicroAppModule();
          addGlobalUncaughtErrorHandler((err) => console.error(err));
          props.install(microApp, resolve);
        } else {
          resolve();
        }
      } catch (err) {
        reject(err);
      }
    });
  }
}

export default MicroApp;
